<template>
  <view class="confirm-page">
    <!-- 收货地址 -->
    <view class="address-section" @tap="selectAddress">
      <view v-if="selectedAddress" class="address-card">
        <view class="address-header">
          <uni-icons type="location-filled" size="20" color="#00C853"></uni-icons>
          <text class="address-label">收货地址</text>
        </view>
        <view class="address-info">
          <view class="contact-row">
            <text class="contact-name">{{ selectedAddress.contactName }}</text>
            <text class="contact-phone">{{ selectedAddress.contactPhone }}</text>
          </view>
          <text class="address-detail">
            {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.street }}
          </text>
        </view>
        <uni-icons type="arrowright" size="16" color="#ccc"></uni-icons>
      </view>
      <view v-else class="no-address">
        <uni-icons type="location" size="20" color="#999"></uni-icons>
        <text class="no-address-text">请选择收货地址</text>
        <uni-icons type="arrowright" size="16" color="#ccc"></uni-icons>
      </view>
    </view>

    <!-- 商家信息 -->
    <view class="merchant-section">
      <view class="merchant-header">
        <text class="merchant-name">{{ merchantName }}</text>
        <text class="delivery-time">预计{{ deliveryTime }}分钟送达</text>
      </view>
      
      <!-- 商品列表 -->
      <view class="goods-list">
        <view 
          v-for="item in cartItems" 
          :key="item.specKey"
          class="goods-item"
        >
          <image :src="item.image" class="goods-image"></image>
          <view class="goods-info">
            <text class="goods-name">{{ item.name }}</text>
            <text v-if="item.specs" class="goods-specs">{{ item.specs }}</text>
            <text class="goods-price">¥{{ item.price }}</text>
          </view>
          <text class="goods-count">x{{ item.count }}</text>
        </view>
      </view>
    </view>

    <!-- 餐具份数 -->
    <view class="tableware-section">
      <view class="section-row">
        <text class="section-label">餐具份数</text>
        <picker mode="selector" :range="tablewareOptions" @change="onTablewareChange">
          <view class="picker-value">
            {{ tablewareOptions[tablewareIndex] }}
            <uni-icons type="arrowright" size="14" color="#ccc"></uni-icons>
          </view>
        </picker>
      </view>
    </view>

    <!-- 备注 -->
    <view class="remark-section">
      <view class="section-row">
        <text class="section-label">备注</text>
        <input 
          v-model="remark" 
          class="remark-input"
          placeholder="口味、偏好等要求"
          :maxlength="50"
        />
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-section">
      <text class="section-title">支付方式</text>
      <view 
        class="payment-item"
        :class="{ active: paymentMethod === 'wechat' }"
        @tap="paymentMethod = 'wechat'"
      >
        <view class="payment-left">
          <image src="/static/wechat-pay.png" class="payment-icon"></image>
          <text class="payment-name">微信支付</text>
        </view>
        <uni-icons 
          v-if="paymentMethod === 'wechat'" 
          type="checkmarkempty" 
          size="24" 
          color="#00C853"
        ></uni-icons>
      </view>
      
      <view 
        class="payment-item"
        :class="{ active: paymentMethod === 'alipay' }"
        @tap="paymentMethod = 'alipay'"
      >
        <view class="payment-left">
          <image src="/static/alipay.png" class="payment-icon"></image>
          <text class="payment-name">支付宝</text>
        </view>
        <uni-icons 
          v-if="paymentMethod === 'alipay'" 
          type="checkmarkempty" 
          size="24" 
          color="#00C853"
        ></uni-icons>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="fee-section">
      <view class="fee-row">
        <text class="fee-label">商品金额</text>
        <text class="fee-value">¥{{ goodsAmount.toFixed(2) }}</text>
      </view>
      <view class="fee-row">
        <text class="fee-label">配送费</text>
        <text class="fee-value">¥{{ deliveryFee.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 底部提交栏 -->
    <view class="submit-bar">
      <view class="price-box">
        <text class="price-label">实付:</text>
        <text class="total-price">¥{{ totalAmount.toFixed(2) }}</text>
      </view>
      <view class="submit-btn" @tap="submitOrder">
        提交订单
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useUserStore } from '@/store/modules/user';
import { getUserAddresses } from '@/api/auth';
import { submitOrder as submitOrderApi } from '@/api/order';

const userStore = useUserStore();

const merchantId = ref(0);
const merchantName = ref('');
const deliveryFee = ref(0);
const deliveryTime = ref(0);
const cartItems = ref<any[]>([]);
const selectedAddress = ref<any>(null);
const remark = ref('');
const paymentMethod = ref('wechat');

// 餐具选项
const tablewareOptions = ['无需餐具', '1份', '2份', '3份', '4份', '5份'];
const tablewareIndex = ref(0);

// 计算商品金额
const goodsAmount = computed(() => 
  cartItems.value.reduce((sum, item) => sum + item.price * item.count, 0)
);

// 计算总金额
const totalAmount = computed(() => goodsAmount.value + deliveryFee.value);

// 页面加载
onLoad(async (options: any) => {
  console.log('订单确认页面加载,参数:', options);
  
  if (options.merchantId && options.cartData) {
    try {
      const data = JSON.parse(decodeURIComponent(options.cartData));
      merchantId.value = Number(options.merchantId);
      merchantName.value = data.merchantName;
      deliveryFee.value = data.deliveryFee;
      deliveryTime.value = data.deliveryTime;
      cartItems.value = data.items;
      
      console.log('解析后的数据:', {
        merchantId: merchantId.value,
        merchantName: merchantName.value,
        cartItems: cartItems.value
      });
      
      // 加载默认地址
      await loadDefaultAddress();
    } catch (error) {
      console.error('解析订单数据失败:', error);
      uni.showToast({
        title: '加载订单信息失败',
        icon: 'none'
      });
    }
  } else {
    console.error('缺少必要参数:', options);
    uni.showToast({
      title: '订单信息不完整',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 加载默认地址
const loadDefaultAddress = async () => {
  try {
    if (!userStore.userInfo || !userStore.userInfo.customerId) {
      console.log('用户未登录,跳过加载地址');
      return;
    }
    
    const addresses = await getUserAddresses(userStore.userInfo.customerId);
    console.log('加载到的地址列表:', addresses);
    
    if (Array.isArray(addresses) && addresses.length > 0) {
      selectedAddress.value = addresses.find((addr: any) => addr.isDefault === 1) || addresses[0];
      console.log('已选择地址:', selectedAddress.value);
    }
  } catch (error) {
    console.error('加载地址失败:', error);
  }
};

// 选择地址
const selectAddress = () => {
  uni.navigateTo({
    url: '/pages/my/address/address?from=orderConfirm'
  });
};

// 选择支付方式
const selectPaymentMethod = (method: string) => {
  paymentMethod.value = method;
};

// 餐具选择
const onTablewareChange = (e: any) => {
  tablewareIndex.value = e.detail.value;
};

// 提交订单
const submitOrder = async () => {
  if (!selectedAddress.value) {
    uni.showToast({ title: '请选择收货地址', icon: 'none' });
    return;
  }
  
  if (!userStore.userInfo?.customerId) {
    uni.showToast({ title: '用户信息异常,请重新登录', icon: 'none' });
    return;
  }
  
  try {
    uni.showLoading({ title: '提交订单中...' });
    
    // 构建备注
    const fullRemark = remark.value + (tablewareIndex.value > 0 ? ` | 餐具${tablewareOptions[tablewareIndex.value]}` : '');
    
    // 构建订单数据
    const orderData = {
      customerId: userStore.userInfo.customerId,
      merchantId: merchantId.value,
      regionId: userStore.userInfo.regionId || 1,
      paymentMethod: paymentMethod.value === 'wechat' ? 1 : 2,
      addressSnapshot: JSON.stringify(selectedAddress.value),
      remark: fullRemark.trim(),
      items: cartItems.value.map(item => ({
        productId: item.id,
        productName: item.name,
        productImage: item.image,
        quantity: item.count,
        unitPrice: item.price,
        tasteOptions: item.specs || ''
      }))
    };
    
    console.log('提交订单数据:', orderData);
    
    // 调用提交订单接口
    const result = await submitOrderApi(orderData);
    console.log('订单API返回:', result);
    
    uni.hideLoading();
    
    // ⭐ 修复263行:根据后端返回结构,orderId在根级别
    // 后端返回: { msg: "操作成功", code: 200, orderId: 53 }
    if (result && (result.orderId || result.data?.orderId)) {
      const orderId = result.orderId || result.data?.orderId;
      console.log('订单创建成功,ID:', orderId);
      goToPay(orderId);
    } else {
      console.error('订单返回数据异常:', result);
      throw new Error('订单创建失败:未返回订单ID');
    }
    
  } catch (error: any) {
    uni.hideLoading();
    console.error('提交订单失败:', error);
    
    // ⭐ 修复265行:安全地访问error属性
    const errorMsg = error?.data?.msg || error?.message || error?.errMsg || '提交订单失败,请重试';
    uni.showToast({ 
      title: errorMsg, 
      icon: 'none',
      duration: 2000
    });
  }
};

// 跳转支付
const goToPay = (orderId: number) => {
  console.log('开始支付流程,订单ID:', orderId);

  // 模拟微信/支付宝支付
  uni.showLoading({ title: '正在支付...' });
  
  setTimeout(() => {
    uni.hideLoading();
    
    // 模拟支付成功(实际应该调用支付接口)
    const paySuccess = Math.random() > 0.3; // 70%概率成功
    
    if (paySuccess) {
      uni.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 1500
      });
      
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/order/detail/detail?id=${orderId}`
        });
      }, 1500);
    } else {
      uni.showModal({
        title: '支付失败',
        content: '支付过程中出现问题,请重试',
        confirmText: '重新支付',
        cancelText: '查看订单',
        success: (res) => {
          if (res.confirm) {
            goToPay(orderId);
          } else {
            uni.redirectTo({
              url: `/pages/order/detail/detail?id=${orderId}`
            });
          }
        }
      });
    }
  }, 2000);
};
</script>

<style scoped>
.confirm-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 150rpx;
}

.address-section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.address-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  gap: 20rpx;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 15rpx;
}

.address-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.address-info {
  flex: 1;
}

.contact-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.contact-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.contact-phone {
  font-size: 28rpx;
  color: #666;
}

.address-detail {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.no-address {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 30rpx;
}

.no-address-text {
  flex: 1;
  margin: 0 20rpx;
  font-size: 28rpx;
  color: #999;
}

.merchant-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.merchant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.merchant-name {
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
}

.delivery-time {
  font-size: 24rpx;
  color: #00C853;
}

.goods-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.goods-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.goods-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
}

.goods-specs {
  font-size: 24rpx;
  color: #999;
}

.goods-price {
  font-size: 28rpx;
  color: #ff3b30;
  font-weight: bold;
}

.goods-count {
  font-size: 26rpx;
  color: #666;
}

.tableware-section,
.remark-section {
  background-color: #fff;
  padding: 0 30rpx;
  margin-bottom: 20rpx;
}

.section-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-label {
  font-size: 28rpx;
  color: #333;
}

.picker-value {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.remark-input {
  flex: 1;
  text-align: right;
  font-size: 28rpx;
  color: #333;
}

.payment-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 20rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.payment-item.active {
  border-color: #00C853;
  background-color: #e6f7ed;
}

.payment-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.payment-icon {
  width: 50rpx;
  height: 50rpx;
}

.payment-name {
  font-size: 28rpx;
  color: #333;
}

.fee-section {
  background-color: #fff;
  padding: 30rpx;
}

.fee-row {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
}

.fee-label {
  font-size: 28rpx;
  color: #666;
}

.fee-value {
  font-size: 28rpx;
  color: #333;
}

.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.05);
}

.price-box {
  display: flex;
  align-items: baseline;
  gap: 10rpx;
}

.price-label {
  font-size: 26rpx;
  color: #666;
}

.total-price {
  font-size: 36rpx;
  color: #ff3b30;
  font-weight: bold;
}

.submit-btn {
  padding: 20rpx 60rpx;
  background-color: #00C853;
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
  border-radius: 40rpx;
}
</style>